package hz.mobileproject.pda.model.attendancemanager.fragment.goabroad;


import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.entity.MessageEvent;
import hz.mobileproject.pda.entity.response.Response_login_user;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.model.attendancemanager.activity.OutDataDetailActivity;
import hz.mobileproject.pda.model.attendancemanager.adapter.OutgoingLvAdapter;
import hz.mobileproject.pda.model.attendancemanager.bean.Rp_queryOutReport;
import hz.mobileproject.pda.model.attendancemanager.bean.Rq_queryOutReport;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.tree.FileBean;
import hz.mobileproject.pda.tree.Node;
import hz.mobileproject.pda.ui.base.BaseFragment;
import hz.mobileproject.pda.ui.view.DeptSelectorDialog;
import hz.mobileproject.pda.ui.view.datepicker.CustomDatePicker;
import hz.mobileproject.pda.utils.HttpRqUtils;

@ContentView(R.layout.fragment_out_all_data)
public class AllGoAbroadDataFragment  extends BaseFragment implements AdapterView.OnItemClickListener, OnLoadmoreListener {
    @ViewInject(R.id.lv_outgoing)
    private ListView lv_outgoing;
    @ViewInject(R.id.smartLayout)
    private SmartRefreshLayout smartRefreshLayout;
    @ViewInject(R.id.iv_show_search)
    private ImageView iv_show_search;
    @ViewInject(R.id.ll_outgoing_search)
    private LinearLayout ll_outgoing_search;
    @ViewInject(R.id.tv_outgoing_begin_time_s)
    private TextView tv_outgoing_begin_time_s;
    @ViewInject(R.id.tv_outgoing_end_time_s)
    private TextView tv_outgoing_end_time_s;
    @ViewInject(R.id.tv_dept_s)
    private TextView tv_dept_s;
    @ViewInject(R.id.tv_police_s)
    private EditText et_police_s;
    @ViewInject(R.id.ll_dept_selector)
    private LinearLayout ll_dept_selector;
    @ViewInject(R.id.tv_count)
    private TextView tv_count;

    private OutgoingLvAdapter mAdapter;
    private List<FileBean> mDeptList;
    private int mPageNum = 1;
    private int mSelectedDeptID = 0;

    @Override
    public void initData() {
        mAdapter = new OutgoingLvAdapter(mContext);
        lv_outgoing.setAdapter(mAdapter);
        lv_outgoing.setOnItemClickListener(this);
        smartRefreshLayout.setOnLoadmoreListener(this);
        EventBus.getDefault().register(this);
        Response_login_user loginUser = MainApp.getInstance().getLoginUser();
        if (loginUser.getIs_leader() == 1) {
            ll_dept_selector.setVisibility(View.VISIBLE);
        } else {
            ll_dept_selector.setVisibility(View.GONE);
        }
        //TODO 获取审批数据
        loadAllOutGoingListData();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCalled(MessageEvent messageEvent) {
        switch (messageEvent.topic){
            case "GoAbroadActivity.loadDeptFromSer":
                mDeptList = (List<FileBean>) messageEvent.what;
                break;
            case "GoAbroadActivity.refreshData":
                //接收消息刷新界面
                emptyData();
                loadAllOutGoingListData();
                break;
            case "GoAbroadActivity.deleteData":
                boolean b = mAdapter.deleteOne((Rp_queryOutReport.OutReportDatas) messageEvent.what);
                ToastUtils.showShort("删除成功");
                if(b){
                    tv_count.setText((Integer.parseInt(tv_count.getText().toString()) - 1) + "");
                }
                break;
        }
    }

    @Event({R.id.iv_right_menu, R.id.iv_show_search, R.id.btn_search, R.id.tv_outgoing_begin_time_s, R.id.tv_outgoing_end_time_s, R.id.tv_dept_s, R.id.tv_police_s})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.btn_search:
                if (!StringUtils.isEmpty(tv_outgoing_begin_time_s.getText()) && !StringUtils.isEmpty(tv_outgoing_end_time_s.getText())) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    long startMillis = TimeUtils.string2Millis(tv_outgoing_begin_time_s.getText().toString(), sdf);
                    long endMillis = TimeUtils.string2Millis(tv_outgoing_end_time_s.getText().toString(), sdf);
                    if (startMillis - endMillis >= 0) {
                        ToastUtils.showShort("开始日期必须小于结束日期");
                        return;
                    }
                }
                if(StringUtils.isEmpty(tv_dept_s.getText())){
                    mSelectedDeptID = 0;
                }
                emptyData();
                loadAllOutGoingListData();
                break;
            case R.id.iv_show_search:
                isShowSearch();
                break;
            case R.id.tv_outgoing_begin_time_s:
                showDatePicker(tv_outgoing_begin_time_s);
                break;
            case R.id.tv_outgoing_end_time_s:
                showDatePicker(tv_outgoing_end_time_s);
                break;
            case R.id.tv_dept_s:
                if (mDeptList == null) {
                    ToastUtils.showShort("未获取到部门数据");
                    return;
                }
                DeptSelectorDialog deptSelectorDialog = new DeptSelectorDialog(mContext, mDeptList);
                deptSelectorDialog.show();
                deptSelectorDialog.setOnPositiveBtnClick(new DeptSelectorDialog.OnPositiveBtnClick() {
                    @Override
                    public void onClick(DeptSelectorDialog dialog, Node node) {
                        dialog.dismiss();
                        tv_dept_s.setText(node.getName());
                        mSelectedDeptID = node.getId();
                    }
                });
                break;
        }
    }

    /**
     * listview点击事件
     *
     * @param adapterView
     * @param view
     * @param i
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Rp_queryOutReport.OutReportDatas item = mAdapter.getItem(i);
        Intent it = new Intent();
        it.setClass(mContext, OutDataDetailActivity.class);
        it.putExtra("key", item);
        it.putExtra("fragmentName", "AllOutDataFragment");
        startActivity(it);
    }


    /**
     * 下拉加载更多
     *
     * @param refreshlayout
     */
    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        loadAllOutGoingListData();
    }


    /**
     * 获取所有数据集合
     */
    private void loadAllOutGoingListData() {
        Rq_queryOutReport rq = new Rq_queryOutReport();
        rq.setOutType(Rq_queryOutReport.OUT_TYPE_GO_ABROAD);
        rq.setQueryType(Rq_queryOutReport.QUERY_TYPE_ALL_DATA);
        rq.setCusNumber(MainApp.getInstance().getLoginUser().getCus_number() + "");
        rq.setPoliceCode(MainApp.getInstance().getLoginUser().getPolice_code());
        rq.setPage(mPageNum);
        rq.setStartDate(tv_outgoing_begin_time_s.getText().toString());
        rq.setEndDate(tv_outgoing_end_time_s.getText().toString());
        rq.setDeptId(mSelectedDeptID);
        rq.setPoliceName(et_police_s.getText().toString());
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_OUTGOING_OUTREPORT, rq, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                smartRefreshLayout.finishLoadmore();
                Rp_queryOutReport rp = mGson.fromJson(data, Rp_queryOutReport.class);
                List<Rp_queryOutReport.OutReportDatas> list = rp.outReportDatas;
                if (list == null || list.size() <= 0) {
                    if (mPageNum == 1) {
                        return;
                    }
                    ToastUtils.showShort("没有更多数据了");
                    return;
                }
                tv_count.setText(rp.count + "");
                mAdapter.addAll(list);
                mPageNum++;
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                LogUtils.e(rtnCode + rtnMsg);
                ToastUtils.showShort("获取数据失败(" + rtnCode + "," + rtnMsg + ")");
                smartRefreshLayout.finishLoadmore();
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                LogUtils.e(ex.toString());
                ToastUtils.showShort("获取数据失败，请检查网络");
                smartRefreshLayout.finishLoadmore();
            }
        });
    }


    private void isShowSearch() {
        if (View.VISIBLE == ll_outgoing_search.getVisibility()) {
            ll_outgoing_search.setVisibility(View.GONE);
            iv_show_search.setImageBitmap(ImageUtils.getBitmap(R.mipmap.xiangxiajiantou));
        } else {
            ll_outgoing_search.setVisibility(View.VISIBLE);
            iv_show_search.setImageBitmap(ImageUtils.getBitmap(R.mipmap.xiangshangjiantou));
        }
    }

    private void showDatePicker(final TextView tv) {
        String selectTime = "";
        if (!StringUtils.isEmpty(tv.getText())) {
            selectTime = tv.getText().toString();
        } else {
            selectTime = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        }
        CustomDatePicker customDatePicker = new CustomDatePicker(mContext, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tv.setText(time.split(" ")[0]);
            }
        }, "1968-01-01 00:00", "2068-01-01 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(false); // 不显示时和分
        customDatePicker.setIsLoop(true); // 循环滚动
        customDatePicker.show(selectTime);
    }


    private void emptyData() {
        mPageNum = 1;
        tv_count.setText("0");
        mAdapter.deleteAll();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
